import EventBus from '../../EventBus'
import { mouseStatus, defaultStoreData, nestComponentTags } from '../../lib/const'
import {
  deepCopy,
  swap,
  stringify,
  setMultipleKeys,
  getComponentListByKeys,
  ergodicList,
  updateComponentKey,
  getParentChildrenByKey,
  getComponentChildren,
  removeComponentByKeys,
  getComponentByKey,
  getOffsetByCanvas,
} from '../../lib/utils'
import { componentToPercentage, componentToPx } from '../../lib/unit'
import initKeyboardEvent from './keyboardEvent'

export default function initEvent(vm) {
  const lowCode = vm.$store.state.lowCode
  // 上一步
  EventBus.$once('snapshotPrev', () => {
    let snapshot = {
      pageSetting: {
        ...defaultStoreData.pageSetting,
      },
      canvasComponentList: [],
    }
    if (lowCode.snapshotIndex >= 1) {
      snapshot = deepCopy(lowCode.snapshotList[lowCode.snapshotIndex - 1])
    }
    vm.setCanvasComponentList(2, snapshot.canvasComponentList, true)
    vm.$store.commit('lowCode/setPageSetting', snapshot.pageSetting)
    vm.$store.commit('lowCode/snapshotPrev')
  })
  // 下一步
  EventBus.$once('snapshotNext', () => {
    const snapshot = deepCopy(lowCode.snapshotList[lowCode.snapshotIndex + 1])
    vm.setCanvasComponentList(2, snapshot.canvasComponentList, true)
    vm.$store.commit('lowCode/setPageSetting', snapshot.pageSetting)
    vm.$store.commit('lowCode/snapshotNext')
  })
  // 删除当前选中
  EventBus.$once('delectSelectedComponent', () => {
    const { multipleKeys, canvasComponentList } = vm
    removeComponentByKeys(canvasComponentList, multipleKeys)
    vm.setCanvasComponentList()
    vm.isContextmenuShow = false
    vm.setSelectedComponent()
    setMultipleKeys([])
    vm.saveSnapshot({
      canvasComponentList: vm.canvasComponentList,
    })
  })
  // 清空画布
  EventBus.$once('deleteAll', () => {
    // vm.canvasComponentList = []
    vm.setCanvasComponentList(2, [])
    vm.setSelectedComponent()
    vm.saveSnapshot({
      canvasComponentList: vm.canvasComponentList,
    })
  })
  // 点击重置
  EventBus.$once('reset', () => {
    // vm.canvasComponentList = []

    vm.$store.commit('lowCode/setSnapshotMinIndex', -1)
    vm.setCanvasComponentList(2, [])
    vm.setSelectedComponent()
    vm.$store.commit('lowCode/resetSnapshot')
  })
  // 点击置底
  EventBus.$once('setAtEndSelectedComponent', () => {
    const { index, parent } = getParentChildrenByKey(vm.canvasComponentList, vm.selectedComponent.key)
    if (index === 0) {
      vm.$message.warn('当前选中组件已处于底部,无须置底')
      return false
    }
    // 替换当前元素和顶部元素的位置
    swap(parent, 0, index)

    vm.setCanvasComponentList()
    vm.saveSnapshot({
      canvasComponentList: vm.canvasComponentList,
    })

    // vm.setSelectedComponent()
    vm.isContextmenuShow = false
  })
  // 点击置顶
  EventBus.$once('toppingSelectedComponent', () => {
    const { index, parent } = getParentChildrenByKey(vm.canvasComponentList, vm.selectedComponent.key)
    if (index === parent.length - 1) {
      vm.$message.warn('当前选中组件已处于顶部,无须置顶')
      return false
    }
    // 替换当前元素和底部元素的位置
    swap(parent, parent.length - 1, index)

    vm.setCanvasComponentList()
    vm.saveSnapshot({
      canvasComponentList: vm.canvasComponentList,
    })

    // vm.setSelectedComponent()
    vm.isContextmenuShow = false
  })
  // 取消选中右键菜单
  EventBus.$once('cancelSelectedComponent', () => {
    vm.isContextmenuShow = false
  })
  // 选中某个组件
  EventBus.$once('selectComponent', (key) => {
    const type = key ? 1 : 2
    const data = key ? getComponentByKey(vm.canvasComponentList, key) : null
    console.log(getComponentByKey(vm.canvasComponentList, key))
    vm.setSelectedComponent(type, {
      data,
    })
  })

  // 修改当前组件并更新到canvasComponentList
  EventBus.$once('setSelectComponentUpdateList', ({ type, data }) => {
    vm.setCanvasComponentList(type, data)
    vm.saveSnapshot({
      canvasComponentList: vm.canvasComponentList,
    })
  })

  // 初始化
  EventBus.$once('init', (data) => {
    vm.setCanvasComponentList(2, data.canvasComponentList)
    vm.$store.commit('lowCode/setSnapshotMinIndex', 0)
    // 清空跳转的过滤条件
    vm.$store.commit('lowCode/setJumpFilterData', {})

    // 清空联动的过滤条件
    vm.$store.commit('lowCode/setLinkageFilterData', [])
    vm.saveSnapshot(data)
  })

  // 点击复制
  EventBus.$once('copy', () => {
    const { selectedComponent, multipleKeys, canvasComponentList } = vm
    const data = getComponentListByKeys(canvasComponentList, multipleKeys)
    vm.$store.commit('lowCode/setClipboardData', deepCopy(data))
    vm.isContextmenuShow = false
  })

  // 点击粘贴
  EventBus.$once('paste', () => {
    const { clipboardData, clipboardStartPositionOffset, multipleKeys, canvasComponentList, selectedComponent } =
      vm.$store.state.lowCode
    const isMultiple = clipboardData.length > 1
    clipboardData.forEach((element, index) => {
      // 先将被粘贴的元素(即clipboardData)以及其所有子元素的key全部更新
      element.key = updateComponentKey(element.id)
      // 获取复制组件的children
      const elementChildren = getComponentChildren(element)
      // 如果当前复制元素有children
      if (elementChildren) {
        // 更新所有子组件的key
        ergodicList(elementChildren, (component) => {
          component.key = updateComponentKey(component.id)
        })
      }

      // 如果是往组件内粘贴,则必有选中的组件selectedComponent
      // 当前组件是粘贴的容器
      // 获取当前组件的children
      const children = getComponentChildren(vm.selectedComponent)
      let parent
      // 如果当前组件有children,那么父组件就不是当前组件
      if (children) {
        parent = children
      }
      // 如果当前组件没有children,那么父组件就不是当前组件,而是当前组件的父组件
      else {
        const data = getParentChildrenByKey(canvasComponentList, vm.selectedComponent.key)
        parent = data.parent
      }
      // 如果点击的是画布
      if (vm.contextmenuType === 'map') {
        parent = canvasComponentList
      }

      const { offsetLeft, offsetTop } = isMultiple
        ? clipboardStartPositionOffset[index]
        : { offsetLeft: 0, offsetTop: 0 }

      const {
        offsetX,
        offsetY,
        offsetTop: parentffsetTop = 0,
        offsetLeft: parentffsetLeft = 0,
      } = vm.contextmenuPosition
      // parentffsetTop, parentffsetLeft即是当前组件的offset
      // parentffsetTop, parentffsetLeft是为了处理鼠标点击在非画布非嵌套组件时, 组件的实际位置 = 鼠标offset + 当前组件的offet
      // 当点击的是嵌套组件时, 不需要parentffsetTop, parentffsetLeft
      const { left: newLeft, top: newTop } = componentToPercentage({
        ...element.style,
        left: offsetX + (nestComponentTags.includes(selectedComponent.tag) ? 0 : parentffsetLeft) + offsetLeft,
        top: offsetY + (nestComponentTags.includes(selectedComponent.tag) ? 0 : parentffsetTop) + offsetTop,
      })

      element.style.left = newLeft
      element.style.top = newTop

      parent.push(deepCopy(element))
    })
    vm.setCanvasComponentList()
    vm.saveSnapshot({
      canvasComponentList: canvasComponentList,
    })
    vm.isContextmenuShow = false
  })

  EventBus.$once('mouseStatusChange', () => {
    vm.$store.commit('lowCode/setMouseStatusChange', mouseStatus.ADD_DRAG)
  })

  // 点击剪切
  EventBus.$once('shear', () => {
    const { selectedComponent, multipleKeys, canvasComponentList } = vm

    // 先复制
    const data = getComponentListByKeys(canvasComponentList, multipleKeys)
    vm.$store.commit('lowCode/setClipboardData', deepCopy(data))
    // 再删除选中的元素
    EventBus.$emit('delectSelectedComponent')
  })

  // 点击组件显示隐藏
  EventBus.$once('setComponentShow', (data) => {
    const { key, isShow } = data

    const component = getComponentByKey(vm.canvasComponentList, key)
    component.isShow = isShow
    vm.setCanvasComponentList()
    vm.saveSnapshot({
      canvasComponentList: vm.canvasComponentList,
    })
  })

  // 查看业务组件数据明细
  EventBus.$once('dataDetails', () => {
    vm.$refs['detailedRef'].show()
    vm.isContextmenuShow = false
  })

  // 监听鼠标滚动
  EventBus.$once('scroll', ({ scrollTop, scrollLeft }) => {
    if (vm.isMultipleShow) {
      vm.scrollOffset.x = scrollLeft
      vm.scrollOffset.y = scrollTop
      // vm.scrollOffset = {
      //   scrollTop,
      //   scrollLeft
      // }
      // vm.multipleEndPosition = {
      //   clientX: vm.multipleEndPosition.clientX + x,
      //   clientY: vm.multipleEndPosition.clientY + y,
      //   offsetX: vm.multipleEndPosition.offsetX + x,
      //   offsetY: vm.multipleEndPosition.offsetY + y
      // }
    } else {
      vm.scrollOffset.scrollLeft = scrollLeft
      vm.scrollOffset.scrollTop = scrollTop
      vm.scrollOffset.x = scrollLeft
      vm.scrollOffset.y = scrollTop
      // vm.scrollOffset = {
      //   x: 0,
      //   y: 0
      // }
    }
    // console.log(vm.scrollOffset)
  })

  // 编辑业务组件
  EventBus.$once('editAnalysis', () => {
    EventBus.$emit('showAnalysisEditor')
    vm.isContextmenuShow = false
  })

  initKeyboardEvent(vm)
}
